package gcontent.db.Search;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import gcontent.Results.Result;
import gcontent.Results.Results;
import gcontent.action.SearchType;
import gcontent.db.BaseDB;
import gcontent.db.DBParams;
import gcontent.db.DBParams.Direction;
import gcontent.utils.Config;

public class Searches extends BaseDB {

	public Searches(boolean autoCommit) throws IOException {
		super(Config.getConfigFile(), autoCommit);
	}
	
	private String generateQueryFromWordAndType(String words, int search_type) {
		String result = "";
		String generatedSentence = "";
		String [] word = words.split(" "); 
		
		generatedSentence = "( path like '%" + words + "%' OR ";
		generatedSentence += "path like '%" + words.replace(" ", ".") + "%' OR ";
		generatedSentence += "path like '%" + words.replace(" ", "-") + "%' OR ";
		generatedSentence += "path like '%" + words.replace(" ", "_") + "%' OR ";
		generatedSentence += "(";
		
		for (int i = 0; i < word.length; i++) {
			generatedSentence += "path like '%" + word[i] + "%'";
			if (i < word.length - 1) {
				generatedSentence += " AND ";
			}
		}
		
		generatedSentence += "))";
		
		switch (search_type)
		{
			case SearchType.TYPE_IMAGES:
				result = "select path, host from site where (path like '%.jpg' or path like '%.png' or path like '%.bmp') and " + generatedSentence;
				break;
			case SearchType.TYPE_CONTENT:
				result = "select path, host from site where 2 = 1";
				break;
			case SearchType.TYPE_ELINKS:
				result = "select path, host from site where (path like '%ed2k:%') and " + generatedSentence;
				break;
			case SearchType.TYPE_TORRENTS:	
				result = "select path, host from site where 2 = 1";
				break;
			case SearchType.TYPE_VIDEOS:
				result = "select path, host from site where 2 = 1";
				break;
			case SearchType.TYPE_ALL:
			default:
				result = "select path, host from site where 2 = 1";
				break;				
		}
		
		return result;
	}
	
	public Results makeSearch(String search_text, int search_type) {
		
		Results res = null;
		ResultSet rs = null;
		String sql = generateQueryFromWordAndType(search_text, search_type);
		
		try {
			this.connect();
			rs = this.executeQuery(sql);
			if (rs != null) {
				res = new Results();				
				while (rs.next ()) {
					res.add(new Result(rs.getString ("path"), rs.getString ("host"), search_type));
				}
				rs.close();
			}
			this.disconnect();
		} catch (SQLException e) {			
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return res;
	}
}
